var vm = new Vue({
    el: "#chat",
    data: {
        //登陆用户
        user: {},
        //好友
        friends: [],
        //好友Map
        friendsMap: {},
        //最近聊天
        recently: [],
        card: 1,
        //是否正在聊天
        isChatting: false,
        //当前聊天好友
        chatting: {
            friend: {
                hisRemark: null,
                myFriend: {}
            },
            messageContextList: []
        },
        //草稿
        draft: {},
        //系统消息条数
        infoNum: 0,
        tempFile: null
    },
    created() {
        //获取用户信息,好友,最近聊天
        this.getUser();
        //连接websocket
        this.linkSock();

    },
    methods: {
        //获取用户信息
        getUser() {
            if (!localStorage.getItem("token")) {
                //无token返回页面
                location.href = "index.html"
            }
            //获取用户信息
            getUserInfo().then(res => {
                if (res.data.errno == 0) {
                    this.user = res.data.data;
                } else {
                    location.href = "index.html"
                }
            }).catch(err => {
                //拒绝请求,回到登陆
                location.href = "index.html"
            });
            //获取用户好友
            getFriend().then(res => {
                if (res.data.errno == 0) {
                    this.friends = res.data.data;
                    this.friends.forEach(friend => {
                        this.friendsMap[friend.myFriendUid] = friend;
                    });
                }
                errInfo(res);
                //获取最近聊天好友
                return getMessage();
            }).then(res => {
                if (res.data.errno == 0) {
                    this.recently = res.data.data;
                    this.recently.forEach(ele => {
                        //获得好友对象 
                        ele.friend = vm.getFriend(ele);
                    });
                }
                errInfo(res);
            });
        },

        //连接websocket
        linkSock() {
            let token = localStorage.getItem('token');
            var sock = new SockJS('http://192.168.22.194:8080/websocket?token=' + token); //连接节点
            var stomp = Stomp.over(sock);
            stomp.connect({}, function (frame) { //连接成功后订阅消息接口
                //订阅个人消息
                stomp.subscribe('/user/queue/msg/new', response => {
                    var res = JSON.parse(response.body);
                    // console.log(response.body);
                    //如果是聊天消息
                    if (res.msgType == 1) {
                        res.data.friend = vm.getFriend(res.data);
                        //判断是否为当前窗口
                        if (vm.chatting.mid == res.data.mid || (!vm.chatting.mid && (vm.chatting.receiveUid == res.data.receiveUid || vm.chatting.receiveUid == res.data.sendUid))) {
                            vm.chatting = res.data;
                            vm.upNotRead();
                            // vm.scrollTop();
                        }
                        vm.addFront(res.data);
                        //如果是系统消息
                    } else if (res.msgType == 2) {
                        //获取系统消息条数
                        layer.open({
                            title: '提示',
                            content: res.data,
                            btn: ['我知道了']
                        });
                        infoWindow.getAddInfo();
                        //刷新好友列表
                    } else if (res.msgType == 3) {
                        layer.open({
                            title: '提示',
                            content: res.data,
                            btn: ['我知道了']
                        });
                        addWindow.getRecoList();
                        vm.refreshFriend();
                    }

                });
                //消息发送结果
                stomp.subscribe('/user/queue/msg/result', response => { });

                //订阅广播消息
                stomp.subscribe('/topic/notice', response => { });
            });
        },
        //刷新好友列表
        refreshFriend() {
            getFriend().then(res => {
                if (res.data.errno == 0) {
                    this.friends = res.data.data;
                    this.friends.forEach(friend => {
                        this.friendsMap[friend.myFriendUid] = friend;
                    });
                }
                errInfo(res);
            })
        },

        getFriend(ele) {
            return ele.sendUid != this.user.uid ? this.friendsMap[ele.sendUid] : this.friendsMap[ele.receiveUid];
        },

        // 显示聊天信息
        chatWindow(mess, i) {
            this.isChatting = true;

            if (i == 1) {
                //查询是否已经有聊天记录
                for (var i = 0; i < this.recently.length; i++) {
                    var res = this.recently[i];
                    if (res.receiveUid == mess.myFriendUid || res.sendUid == mess.myFriendUid) {
                        this.chatting = res;
                        this.upNotRead();
                        this.scrollTop();
                        return;
                    }
                }
                //没有则新建一个空聊天记录
                this.chatting = {
                    sendUid: this.user.uid,
                    receiveUid: mess.myFriendUid,
                    friend: mess,
                    messageContextList: []
                };
                return;
            }
            this.chatting = mess;
            this.upNotRead();
            this.scrollTop();
        },

        upNotRead() {
            // 更新已读 /判断是否存在未读消息
            if (this.countNotRead(this.chatting)) {
                upNotRead(this.chatting.mid).then(res => {
                    if (res.data.errno == 0) {
                        this.chatting.messageContextList.forEach(mc => {
                            if (mc.sendUid != this.user.uid) {
                                mc.viewState = 0;
                            }
                        });
                    }
                    errInfo(res);
                })
            }
        },

        //文本域回车发送消息
        sendEnter(e) {
            var keyCode = e.keyCode || e.which || e.charCode;
            var ctrlKey = e.ctrlKey || e.metaKey;
            // 判断 ctrl+enter 换行
            if (ctrlKey && keyCode == 13) {
                insertContent("<br/>");
                return false;
            } else if (keyCode === 13) {
                e.preventDefault(); // 阻止浏览器默认换行操作
                this.sendMC(); // 发送信息
                return false;
            }
        },

        //发送信息
        sendMC(text, type) {
            //接收人Id
            let ruid = this.chatting.friend.myFriendUid;
            //TODO 校验

            //内容为空,不发送
            if (!this.draft[ruid] && !text) {
                return;
            }
            //创建聊天内容
            var mc = {
                // text: "<div>" + this.draft[ruid].replace(/(\r\n)|(\n)/g, '</div><div>') + "</div>",
                text: this.draft[ruid] ? this.draft[ruid] : text,
                mcType: type ? type : "text",
                sendUid: this.user.uid,
                sendDate: new Date().getTime(),
                receiveUid: ruid,
                viewState: 1,
                mid: this.chatting.mid
            };

            //清空
            this.draft[ruid] = "";
            $("#textarea").text("");
            $("#textarea").html("");

            //添加到本地
            this.chatting.messageContextList.push(mc);

            //发送消息+图片/文件
            if (text) {
                let param = new FormData(); //创建form对象
                param.append('file', this.tempFile);//通过append向form对象添加数据
                param.append('type', mc.mcType);

                //发送文件
                sendFileToServer(param).then(res => {
                    errInfo(res);
                    if (res.data.errno == 0) {
                        mc.text = res.data.data;
                        return sendMC(mc);
                    }
                    //消息回调
                }).then(res => {
                    this.callBack(res);
                });

            } else {
                //调用api发送消息
                sendMC(mc).then(res => {
                    this.callBack(res);
                });
            }

        },
        //发送消息回调
        callBack(res) {
            if (res) {
                if (res.data.errno == 0) {
                    if (this.chatting.receiveUid == res.data.data.receiveUid || this.chatting.receiveUid == res.data.data.sendUid) {
                        this.chatting = res.data.data;
                        this.chatting.friend = this.getFriend(this.chatting);
                        this.addFront(this.chatting);
                        this.scrollTop();
                    }
                }
                errInfo(res);
            }
        },

        //滑动条到最下面
        scrollTop() {
            /*DOM更新后执行*/
            this.$nextTick(function () {
                var div = document.getElementById('msgWindows');
                setTimeout(function () {
                    div.scrollTop = div.scrollHeight;
                }, 50)
            })

        },
        //更新最近聊天,排序到前面
        addFront(data) {
            //更新聊天记录循序
            var newArr = new Array();
            newArr.push(data);
            this.recently.forEach(ele => {
                if (ele.mid != data.mid) {
                    newArr.push(ele);
                }
            });
            //更新最新聊天顺序
            this.recently = newArr;
        },

        //获取未读消息条数
        countNotRead(msg) {
            var count = 0;
            msg.messageContextList.forEach(mc => {
                if (mc.viewState && mc.sendUid != this.user.uid) {
                    count++;
                }
            });
            return count;
        },
        //显示未读条数
        showNotRead(msg) {
            if (this.chatting.mid == msg.mid) {
                return "";
            }
            var count = this.countNotRead(msg)
            return count ? count : "";
        },
        //显示所有未读信息条数
        showAllNotRead() {
            var count = 0;
            this.recently.forEach(msg => {
                msg.messageContextList.forEach(mc => {
                    if (mc.viewState && mc.sendUid != this.user.uid && this.chatting.mid != mc.mid) {
                        count++;
                    }
                })
            });
            return count ? count : "";
        },
        //显示最新的一条消息
        showNewestInfo(mess) {
            if (!mess.messageContextList.length) {
                return "暂无消息!"
            }
            var mc = mess.messageContextList[mess.messageContextList.length - 1];
            if (mc.mcType == "text") {
                return this.newDispose(mc.text);
            } else if (mc.mcType == "image") {
                return "[图片]";
            } else if (mc.mcType == "file") {
                return "[文件]";
            }
        },

        //最新消息最后一条显示处理
        newDispose(text) {
            //处理换行
            text = text.replace(new RegExp("</div><div>", "g"), '&nbsp;')
            text = text.replace(new RegExp("<div>", "g"), '')
            text = text.replace(new RegExp("<br>", "g"), '&nbsp;')
            text = text.replace(new RegExp("</div>", "g"), '')
            return text;
        },
        //显示信息处理
        dispose(mc) {
            if (mc.mcType == "text") {
                return mc.text;
            } else if (mc.mcType == "image") {
                return `<img class="picture" src="` + mc.text + `">`;
            } else if (mc.mcType == "file") {
                var name = mc.text.substring(mc.text.lastIndexOf("\\") + 1);
                return `<a href="` + mc.text + `" target="view_window">[文件]` + name + `</a>`;
            }
        },
        //打开表情
        showFace() {
            layer.open({
                type: 2,
                title: null,
                area: ['550px', '300px'],
                skin: 'layui-layer-rim', //加上边框
                shadeClose: true,
                content: ['face.html', 'no']
            });
        },

    },
});